<?php
class Core_Dice
{
	const REGEX			= '/(\d+)?d(\d+)[\s+]?([\+\*\-\/])?[\s+]?(\d+)?/';
	const ROUND_UP		= 0x1;
	const ROUND_DOWN	= 0x2;
		
	public static function roll($dice, $times = 1, $round = self::ROUND_DOWN)
	{
		//quick and dirty to allow for d% to be used
		$dice	= str_replace('d%', 'd100', $dice);
		Zend_Loader::loadClass('Core_Dice_Validate');
		$valid	= new Core_Dice_Validate();
		
		if (!$valid->isValid($dice))
		{
			$err	= $valid->getErrors();
			throw new Exception($err[0]);
		}
		
		if (preg_match(self::REGEX, $dice, $m) < 1)
		{
			throw new Exception('Invalid Dice Roll: No Matchs');
		}
		
		$rolls = array();
		for ($i = 1; $i <= $times; $i++)
		{
			$diceNum	= (!$m[1]) ? 1 : $m[1];
			$roll		= 0;
			
			for($rollCount = 0; $rollCount < $diceNum; $rollCount++)
			{
				$roll		+= mt_rand(1, $m[2]);	
			}
			
			//modifer
			if (array_key_exists(4, $m) && array_key_exists(3, $m))
			{
				switch($m[3])
				{
					case '+':
						$roll 	+= $m[4];
						break;
					case '*':
						$roll 	*= $m[4];
						break;
					case '/':
						if ($round == self::ROUND_UP)
						{
							$roll	= ceil($roll / $m[4]);
						}
						else if ($round == self::ROUND_DOWN)
						{
							$roll	= floor($roll / $m[4]);
						}
						else 
						{
							Zend_Loader::loadClass('Core_Exception');
							throw new Core_Exception();
						}
						break;
					case '-':
						$roll	-= $m[4];
						break;
				}
			}
			
			$rolls[$i]	= $roll; 
		}
		
		return $rolls;
	}
}